/**
 * Projet Multicast Bidois Morgan & Thomas Nunes
 *
 */
package Test;

import Gui.I_ChatClient;
import middleware.ClientMulticast;
import Gui.ChatException;
import Gui.ChatGUI;
import Engine.*;

/**
 *
 * @author Thomas
 *
 * Launch a client
 */
public class ExecuteClient implements I_ChatClient, I_RecvMsgHandler {

    private String name;
    private ClientMulticast client;
    private ChatGUI gui;
    private boolean connecte = false;

    public ExecuteClient() {
        gui = new ChatGUI();

        gui.setHandler(this);
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            System.out.println("sleep exception.");
        }
    }

    public static void main(String[] args) {
        ExecuteClient c = new ExecuteClient();
    }

    @Override
    public void register(String clientName) throws ChatException {
        if (!connecte) {
            client = new ClientMulticast(this);
            client.start();
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
                System.out.println("sleep exception.");
            }
            client.registerAsClient(clientName);
            connecte = true;
            gui.printMsg("En cours de connexion...");
        }
    }

    @Override
    public void leave() throws ChatException {
        if (connecte) {
            gui.printMsg("**Deconnection**");
            client.terminate();
            connecte = false;
            client = null;
        } else {
            gui.printMsg("Vous n'êtes pas connecté.");
        }
    }

    @Override
    public void who() throws ChatException {
        if (connecte) {
            String res = this.client.getAllClientName();
            gui.printMsg(res);
        } else {
            gui.printMsg("Vous n'êtes pas connecté.");
        }
    }

    @Override
    public void sendMsgToGroup(String msg) throws ChatException {
        client.sendMsg2All(msg.getBytes(), TypeMessage.NORMAL);
    }

    @Override
    public void quit() throws ChatException {
        this.leave();
        System.exit(1);
    }

    @Override
    public void deliverCB(byte[] data) {
        gui.printMsg(new String(data));
    }

    @Override
    public void nbClientCurrentCB(int countClient) {
    }

    @Override
    public void updateOrdered(boolean ordered, int lc) {
    }
}
